package com.pucong.gitee.database.backup.business.database.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.pucong.gitee.database.backup.business.database.mapper.AutoDataSourceMapper;
import com.pucong.gitee.database.backup.business.database.mapper.AutoExeSqlLogMapper;
import com.pucong.gitee.database.backup.business.database.util.BackupServiceFactory;
import com.pucong.gitee.database.backup.business.database.util.OperationService;
import com.pucong.gitee.database.backup.business.sys.mapper.SysFileMapper;
import com.pucong.gitee.database.backup.common.entity.database.AutoDataSource;
import com.pucong.gitee.database.backup.common.entity.database.dto.*;
import com.pucong.gitee.database.backup.common.entity.database.vo.*;
import com.pucong.gitee.database.backup.common.entity.sys.SysFile;
import com.pucong.gitee.database.backup.common.entity.sys.UserJwt;
import com.pucong.gitee.database.backup.common.entity.websock.DatabaseTableWebsocketVo;
import com.pucong.gitee.database.backup.common.selfenum.DatabaseTableStatusEnum;
import com.pucong.gitee.database.backup.common.selfenum.FileStatusEnum;
import com.pucong.gitee.database.backup.configuration.exception.BusinessException;
import com.pucong.gitee.database.backup.utils.*;
import com.pucong.gitee.database.backup.utils.UUID;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.websocket.Session;
import java.io.*;
import java.sql.Timestamp;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OperationDataTableServiceImpl implements OperationDataTableService {

    @Autowired
    private AutoDataSourceMapper autoDataSourceMapper;

    @Autowired
    private BackupServiceFactory backupServiceFactory;

    @Autowired
    private OperationDataSqlService operationDataSqlService;

    @Autowired
    private AutoExeSqlLogMapper autoExeSqlLogMapper;

    @Autowired
    private DatabaseStaticService databaseStaticService;

    @Autowired
    private SysFileMapper sysFileMapper;

    //存放连接信息的map
    private static Map<String, Session> sqlExecMap = new ConcurrentHashMap<>();

    @Override
    public List<DatabaseTableVo> getTableList(DatabaseTableDto dto) {
        AutoDataSource db = autoDataSourceMapper.selectById(dto.getDataSourceId());
        db.setDatabaseName(dto.getDatabaseName());
        db.setSchemaName(dto.getSchemaName());
        // 查询数据源下的数据库
        OperationService operationService = backupServiceFactory.getBackupService(db, autoExeSqlLogMapper);
        List<DatabaseTableVo> tableList = operationService.getTableListByDBInfo(dto.getDatabaseName(), dto.getSchemaName());
        operationService.closeAll();
        return tableList;
    }

    @Override
    public RunSqlResultPage getTableData(String sessionId, DatabaseTableDataDto dto) {
        OperationService operationService = databaseStaticService.getConnectionById(sessionId, dto.getDataSourceId(), dto.getDatabaseName(), dto.getSchemaName());
        RunSqlResultPage exeSqlResult = operationService.executeQueryPage(dto.getPageNum(), dto.getPageSize(), "select * from " + dto.getTableName(), null);
        operationService.closeAll();
        return exeSqlResult;
    }

    @Override
    public void doMsg(String message, Session session) {
        ObjectMapper objectMapper = new ObjectMapper();
        DatabaseTableDdlDto dto = null;
        try {
            dto = objectMapper.readValue(message, DatabaseTableDdlDto.class);
        } catch (IOException e) {
            log.error("Json转换异常");
            log.error("异常信息:{}", e);
            throw new BusinessException("传入参数错误");
        }
        // 校验用户信息
        String token = dto.getToken();
        UserJwt userJwt = operationDataSqlService.checkUserPermission(token, dto.getDataSourceId());
        // 处理消息
        // 启动线程异步处理
        DatabaseTableDdlDto finalDto = dto;
        ThreadPoolUtils.executor(() -> {
            try {
                if (finalDto.getExeStatusEnum() == DatabaseTableStatusEnum.删除表) {
                    deleteTable(userJwt.getUuid(), finalDto);
                    // 发送消息
                    DatabaseTableWebsocketVo vo = new DatabaseTableWebsocketVo();
                    vo.setExeStatusEnum(finalDto.getExeStatusEnum());
                    vo.setExecSuccess(true);

                    String resStr = objectMapper.writeValueAsString(vo);
                    session.getBasicRemote().sendText(resStr);
                } else if (finalDto.getExeStatusEnum() == DatabaseTableStatusEnum.清空表数据) {
                    clearTableData(userJwt.getUuid(), finalDto);
                    // 发送消息
                    DatabaseTableWebsocketVo vo = new DatabaseTableWebsocketVo();
                    vo.setExeStatusEnum(finalDto.getExeStatusEnum());
                    vo.setExecSuccess(true);

                    String resStr = objectMapper.writeValueAsString(vo);
                    session.getBasicRemote().sendText(resStr);
                } else if (finalDto.getExeStatusEnum() == DatabaseTableStatusEnum.删除数据) {
                    deleteTableData(userJwt.getUuid(), finalDto);
                    // 发送消息
                    DatabaseTableWebsocketVo vo = new DatabaseTableWebsocketVo();
                    vo.setExeStatusEnum(finalDto.getExeStatusEnum());
                    vo.setExecSuccess(true);

                    String resStr = objectMapper.writeValueAsString(vo);
                    session.getBasicRemote().sendText(resStr);
                } else if (finalDto.getExeStatusEnum() == DatabaseTableStatusEnum.导出ddl) {
                    String tableDdl = getTableDdl(userJwt.getUuid(), finalDto);
                    // 发送消息
                    DatabaseTableWebsocketVo vo = new DatabaseTableWebsocketVo();
                    vo.setExeStatusEnum(finalDto.getExeStatusEnum());
                    vo.setFileId(tableDdl);
                    vo.setExecSuccess(true);

                    String resStr = objectMapper.writeValueAsString(vo);
                    session.getBasicRemote().sendText(resStr);
                } else if (finalDto.getExeStatusEnum() == DatabaseTableStatusEnum.导出dml) {
                    String tableDml = getTableDml(userJwt.getUuid(), finalDto);
                    // 发送消息
                    DatabaseTableWebsocketVo vo = new DatabaseTableWebsocketVo();
                    vo.setExeStatusEnum(finalDto.getExeStatusEnum());
                    vo.setFileId(tableDml);
                    vo.setExecSuccess(true);

                    String resStr = objectMapper.writeValueAsString(vo);
                    session.getBasicRemote().sendText(resStr);
                } else if (finalDto.getExeStatusEnum() == DatabaseTableStatusEnum.导出数据到excel) {
                    String fileId = downloadTable2Excel(userJwt.getUuid(), finalDto);
                    // 发送消息
                    DatabaseTableWebsocketVo vo = new DatabaseTableWebsocketVo();
                    vo.setExeStatusEnum(finalDto.getExeStatusEnum());
                    vo.setFileId(fileId);
                    vo.setExecSuccess(true);

                    String resStr = objectMapper.writeValueAsString(vo);
                    session.getBasicRemote().sendText(resStr);
                } else if (finalDto.getExeStatusEnum() == DatabaseTableStatusEnum.导出数据到csv) {
                    String fileId = downloadTable2Csv(userJwt.getUuid(), finalDto);
                    // 发送消息
                    DatabaseTableWebsocketVo vo = new DatabaseTableWebsocketVo();
                    vo.setExeStatusEnum(finalDto.getExeStatusEnum());
                    vo.setFileId(fileId);
                    vo.setExecSuccess(true);

                    String resStr = objectMapper.writeValueAsString(vo);
                    session.getBasicRemote().sendText(resStr);
                }
            } catch (Exception e) {
                // 发送异常消息
                try {
                    DatabaseTableWebsocketVo vo = new DatabaseTableWebsocketVo();
                    vo.setExeStatusEnum(finalDto.getExeStatusEnum());
                    vo.setExecSuccess(false);
                    vo.setErrorContent(e.getMessage());

                    String resStr = objectMapper.writeValueAsString(vo);
                    session.getBasicRemote().sendText(resStr);
                } catch (IOException e2) {
                    log.error("发送消息失败:", e2);
                    throw new BusinessException("发送消息失败");
                }
            }
        });
    }

    @Override
    public List<String> getDataDmlSql(DatabaseTableDataDmlDto dto) {
        List<String> insertSqlListByList = SqlUtils.getInsertSqlListByList(dto.getDataList(), dto.getTableName());
        return insertSqlListByList;
    }

    @Override
    public String getTableDdl(String userId, DatabaseTableDdlDto dto) throws Exception {
        List<String> tableNameList = dto.getTableNameList();
        List<String> filePathList = new ArrayList<>(tableNameList.size());

        OperationService operationService = databaseStaticService.getConnectionById(userId, dto.getDataSourceId(), dto.getDatabaseName(), dto.getSchemaName());

        for (String tableName : tableNameList) {
            String filePath = operationService.getDdl(tableName);
            filePathList.add(filePath);
        }
        operationService.closeAll();
        // 合并文件
        String filePath = ApplicationContextUtil.getTmpPath() + File.separator + UUID.uuid() + "ddl.sql";
        File file = new File(filePath);
        BufferedWriter bw = new BufferedWriter(new FileWriter(file));
        for (String filePath2 : filePathList) {
            File file2 = new File(filePath2);
            BufferedReader reader = new BufferedReader(new FileReader(file2));
            String line = "";
            while ((line = reader.readLine()) != null) {
                bw.write(line);
                bw.newLine();
            }
            reader.close();
        }
        bw.close();
        // 新增文件记录
        SysFile sysFile = new SysFile();
        sysFile.setUuid(UUID.uuid());
        sysFile.setFileSize(file.length() + "");
        sysFile.setFileNameOld(UUID.getSerializNo() + "ddl.sql");
        sysFile.setFileType("sql");

        sysFile.setCreateTime(new Date());
        sysFile.setCreateBy(userId);
        sysFile.setFileName(file.getName());
        sysFile.setFileStatus(FileStatusEnum.临时文件);
        sysFile.setPath(filePath);
        sysFileMapper.insert(sysFile);
        return sysFile.getUuid();
    }

    @Override
    public String getTableDml(String userId, DatabaseTableDdlDto dto) {
        List<String> tableNameList = dto.getTableNameList();
        List<String> filePathList = new ArrayList<>(tableNameList.size());

        OperationService operationService = databaseStaticService.getConnectionById(userId, dto.getDataSourceId(), dto.getDatabaseName(), dto.getSchemaName());
        for (String tableName : tableNameList) {
            String filePath = operationService.getDml(tableName);
            filePathList.add(filePath);
        }
        operationService.closeAll();
        // 生成压缩包
        String zipFilePath = FileUtil.createZipFile(filePathList);
        File file = new File(zipFilePath);
        // 新增文件记录
        SysFile sysFile = new SysFile();
        sysFile.setUuid(UUID.uuid());
        sysFile.setFileSize(file.length() + "");
        sysFile.setFileNameOld(UUID.getSerializNo() + "dml.zip");
        sysFile.setFileType("zip");

        sysFile.setCreateTime(new Date());
        sysFile.setCreateBy(userId);
        sysFile.setFileName(file.getName());
        sysFile.setFileStatus(FileStatusEnum.临时文件);
        sysFile.setPath(zipFilePath);
        sysFileMapper.insert(sysFile);
        return sysFile.getUuid();
    }

    @Override
    public String downloadTable2Excel(String userId, DatabaseTableDdlDto dto) throws Exception {
        List<String> tableNameList = dto.getTableNameList();
        List<String> filePathList = new ArrayList<>(tableNameList.size());

        OperationService operationService = databaseStaticService.getConnectionById(userId, dto.getDataSourceId(), dto.getDatabaseName(), dto.getSchemaName());
        for (String tableName : tableNameList) {
            String filePath = ApplicationContextUtil.getTmpPath() + File.separator + tableName + UUID.getSerializNo() + ".xlsx";
            FileOutputStream fos = new FileOutputStream(filePath);
            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet(UUID.getSerializNo());
            int rowIndex = 0;
            String sql = "select * from " + tableName;
            Integer pageSize = 10000;
            for (Integer pageNum = 1; ; pageNum++) {
                // 分页查询
                RunSqlResultPage runSqlResultPage = operationService.executeQueryPage(pageNum, pageSize, sql, null);
                List<ResultFiledVo> filedList = runSqlResultPage.getFiledList();
                List<Map<String, Object>> valueList = runSqlResultPage.getExecResultMapPage().getRecords();
                int columnIndex = 0;
                if (pageNum == 1) {
                    // 设置表头
                    List<String> filedList2 = filedList.stream().map(ResultFiledVo::getFiledName).collect(Collectors.toList());
                    Row row = sheet.createRow(rowIndex++);
                    for (String key : filedList2) {
                        Cell cell = row.createCell(columnIndex++);
                        cell.setCellValue(key);
                    }
                }
                if (valueList.size() == 0) {
                    break;
                }
                // 设置数据
                if (valueList != null && !valueList.isEmpty()) {
                    for (Map<String, Object> map : valueList) {
                        Row row = sheet.createRow(rowIndex++);
                        columnIndex = 0;
                        Collection<Object> values = map.values();
                        Object[] valueStrs = values.toArray(new Object[values.size()]);
                        for (Object value : valueStrs) {
                            Cell cell = row.createCell(columnIndex++);
                            setCellValue(cell, value);
                        }
                    }
                }
            }
            workbook.write(fos);
            fos.flush();
            fos.close();
            filePathList.add(filePath);
        }
        operationService.closeAll();
        // 生成压缩包
        String zipFilePath = FileUtil.createZipFile(filePathList);
        File file = new File(zipFilePath);
        // 新增文件记录
        SysFile sysFile = new SysFile();
        sysFile.setUuid(UUID.uuid());
        sysFile.setFileSize(file.length() + "");
        sysFile.setFileNameOld(file.getName());
        sysFile.setFileType("zip");

        sysFile.setCreateTime(new Date());
        sysFile.setCreateBy(userId);
        sysFile.setFileName(file.getName());
        sysFile.setFileStatus(FileStatusEnum.临时文件);
        sysFile.setPath(zipFilePath);
        sysFileMapper.insert(sysFile);
        return sysFile.getUuid();
    }

    private static void setCellValue(Cell cell, Object obj) {
        if (obj == null) {
            return;
        }
        if (obj instanceof String) {
            cell.setCellValue((String) obj);
        } else if (obj instanceof Date) {
            Date date = (Date) obj;
            if (date != null) {
                cell.setCellValue(date);
            }
        } else if (obj instanceof Calendar) {
            Calendar calendar = (Calendar) obj;
            if (calendar != null) {
                cell.setCellValue(calendar);
            }
        } else if (obj instanceof Timestamp) {
            Timestamp timestamp = (Timestamp) obj;
            if (timestamp != null) {
                cell.setCellValue(timestamp);
            }
        } else if (obj instanceof Double) {
            cell.setCellValue((Double) obj);
        } else {
            cell.setCellValue(obj.toString());
        }
    }

    @Override
    public String downloadTable2Csv(String userId, DatabaseTableDdlDto dto) throws Exception {
        List<String> tableNameList = dto.getTableNameList();
        List<String> filePathList = new ArrayList<>(tableNameList.size());

        OperationService operationService = databaseStaticService.getConnectionById(userId, dto.getDataSourceId(), dto.getDatabaseName(), dto.getSchemaName());
        for (String tableName : tableNameList) {
            String filePath = ApplicationContextUtil.getTmpPath() + File.separator + tableName + UUID.getSerializNo() + ".csv";
            FileOutputStream fos = new FileOutputStream(filePath);
            Integer pageSize = 10000;
            String sql = "select * from " + tableName;
            // 导出数据
            OutputStreamWriter osw = new OutputStreamWriter(fos, "GBK");
            CSVPrinter csvPrinter = null;
            for (Integer pageNum = 1; ; pageNum++) {
                // 分页查询
                RunSqlResultPage runSqlResultPage = operationService.executeQueryPage(pageNum, pageSize, sql, null);
                List<ResultFiledVo> filedList = runSqlResultPage.getFiledList();
                List<Map<String, Object>> valueList = runSqlResultPage.getExecResultMapPage().getRecords();
                if (pageNum == 1) {
                    // 设置表头
                    List<String> filedList2 = filedList.stream().map(ResultFiledVo::getFiledName).collect(Collectors.toList());
                    String[] filedStrs = filedList2.toArray(new String[filedList2.size()]);
                    CSVFormat csvFormat = CSVFormat.DEFAULT.withHeader(filedStrs);
                    csvPrinter = new CSVPrinter(osw, csvFormat);
                }
                if (valueList.size() == 0) {
                    break;
                }
                // 设置数据
                for (int j = 0; j < valueList.size(); j++) {
                    Map<String, Object> stringObjectMap = valueList.get(j);
                    Collection<Object> values = stringObjectMap.values();
                    Object[] valueStrs = values.toArray(new Object[values.size()]);
                    csvPrinter.printRecord(valueStrs);
                }
            }
            csvPrinter.flush();
            csvPrinter.close();
            fos.flush();
            fos.close();
            filePathList.add(filePath);
        }
        operationService.closeAll();
        // 生成压缩包
        String zipFilePath = FileUtil.createZipFile(filePathList);
        File file = new File(zipFilePath);
        // 新增文件记录
        SysFile sysFile = new SysFile();
        sysFile.setUuid(UUID.uuid());
        sysFile.setFileSize(file.length() + "");
        sysFile.setFileNameOld(file.getName());
        sysFile.setFileType("zip");

        sysFile.setCreateTime(new Date());
        sysFile.setCreateBy(userId);
        sysFile.setFileName(file.getName());
        sysFile.setFileStatus(FileStatusEnum.临时文件);
        sysFile.setPath(zipFilePath);
        sysFileMapper.insert(sysFile);
        return sysFile.getUuid();
    }

    @Override
    public Boolean deleteTable(String userId, DatabaseTableDdlDto dto) {
        List<String> tableNameList = dto.getTableNameList();
        OperationService operationService = databaseStaticService.getConnectionById(userId, dto.getDataSourceId(), dto.getDatabaseName(), dto.getSchemaName());
        for (String tableName : tableNameList) {
            operationService.dropTable(tableName);
        }
        operationService.closeAll();
        return true;
    }

    @Override
    public Boolean clearTableData(String userId, DatabaseTableDdlDto dto) {
        List<String> tableNameList = dto.getTableNameList();
        OperationService operationService = databaseStaticService.getConnectionById(userId, dto.getDataSourceId(), dto.getDatabaseName(), dto.getSchemaName());
        for (String tableName : tableNameList) {
            operationService.clearTableData(tableName);
        }
        operationService.closeAll();
        return true;
    }

    @Override
    public Boolean deleteTableData(String userId, DatabaseTableDdlDto dto) {
        List<Map<String, Object>> dataList = dto.getDataList();
        if (dataList.size() > 0) {
            OperationService operationService = databaseStaticService.getConnectionById(userId, dto.getDataSourceId(), dto.getDatabaseName(), dto.getSchemaName());
            operationService.deleteTableData(dto.getTableName(), dataList);
            operationService.closeAll();
        }
        return true;
    }

    @Override
    public void initConnection(Session session) {
        String uuid = session.getId();
        sqlExecMap.put(uuid, session);
    }

    @Override
    public void close(Session session) {
        String id = session.getId();
        //map中移除
        sqlExecMap.remove(id);
    }

    @Override
    public List<DatabaseTableFiledVo> getTableFiledList(DatabaseTableDataDto dto) {
        UserJwt loginUser = UserRequest.getLoginUser();
        OperationService operationService = databaseStaticService.getConnectionById(loginUser.getUuid(), dto.getDataSourceId(), dto.getDatabaseName(), dto.getSchemaName());
        List<DatabaseTableFiledVo> tableFiledListByDBInfo = operationService.getTableFiledListByDBInfo(dto.getDatabaseName(), dto.getSchemaName(), dto.getTableName());
        operationService.closeAll();
        return tableFiledListByDBInfo;
    }

    @Override
    public Boolean toUp(DatabaseTableFiledDto dto) {
        UserJwt loginUser = UserRequest.getLoginUser();
        OperationService operationService = databaseStaticService.getConnectionById(loginUser.getUuid(), dto.getDataSourceId(), dto.getDatabaseName(), dto.getSchemaName());
        operationService.toUp(dto.getTableName(), dto.getFiledName());
        operationService.closeAll();
        return true;
    }

    @Override
    public Boolean toDown(DatabaseTableFiledDto dto) {
        UserJwt loginUser = UserRequest.getLoginUser();
        OperationService operationService = databaseStaticService.getConnectionById(loginUser.getUuid(), dto.getDataSourceId(), dto.getDatabaseName(), dto.getSchemaName());
        operationService.toDown(dto.getTableName(), dto.getFiledName());
        operationService.closeAll();
        return true;
    }

    @Override
    public Boolean deleteFiled(DatabaseTableFiledDto dto) {
        UserJwt loginUser = UserRequest.getLoginUser();
        OperationService operationService = databaseStaticService.getConnectionById(loginUser.getUuid(), dto.getDataSourceId(), dto.getDatabaseName(), dto.getSchemaName());
        operationService.deleteFiled(dto.getTableName(), dto.getFiledName());
        operationService.closeAll();
        return true;
    }

    @Override
    public String[] getTableFiledTypeList(String dataSourceId) {
        AutoDataSource autoDataSource = autoDataSourceMapper.selectById(dataSourceId);
        if (autoDataSource == null) {
            throw new BusinessException("获取数据库异常，未找到数据");
        }
        OperationService operationService = backupServiceFactory.getBackupService(autoDataSource, autoExeSqlLogMapper);
        String[] typeList = operationService.getTableFiledTypeList();
        return typeList;
    }

    @Override
    public Boolean addFiled(DatabaseTableFiledAddDto dto) {
        UserJwt loginUser = UserRequest.getLoginUser();
        OperationService operationService = databaseStaticService.getConnectionById(loginUser.getUuid(), dto.getDataSourceId(), dto.getDatabaseName(), dto.getSchemaName());
        operationService.addFiled(dto.getTableName(), dto.getFiledVo());
        operationService.closeAll();
        return true;
    }

    @Override
    public Boolean updateFiled(DatabaseTableFiledUpdateDto dto) {
        UserJwt loginUser = UserRequest.getLoginUser();
        OperationService operationService = databaseStaticService.getConnectionById(loginUser.getUuid(), dto.getDataSourceId(), dto.getDatabaseName(), dto.getSchemaName());
        operationService.updateFiled(dto.getTableName(), dto.getFiledNameOld(), dto.getFiledVo());
        operationService.closeAll();
        return true;
    }

    @Override
    public List<DatabaseTableIndexVo> getTableIndexList(DatabaseTableIndexSelectDto dto) {
        UserJwt loginUser = UserRequest.getLoginUser();
        OperationService operationService = databaseStaticService.getConnectionById(loginUser.getUuid(), dto.getDataSourceId(), dto.getDatabaseName(), dto.getSchemaName());
        List<DatabaseTableIndexVo> indexVoList = operationService.getTableIndexList(dto.getSchemaName(), dto.getTableName());
        operationService.closeAll();
        return indexVoList;
    }

    @Override
    public Boolean addIndex(DatabaseTableIndexAddDto dto) {
        UserJwt loginUser = UserRequest.getLoginUser();
        OperationService operationService = databaseStaticService.getConnectionById(loginUser.getUuid(), dto.getDataSourceId(), dto.getDatabaseName(), dto.getSchemaName());
        operationService.addIndex(dto.getSchemaName(), dto.getTableName(), dto.getIndexDto());
        operationService.closeAll();
        return true;
    }

    @Override
    public Boolean updateIndex(DatabaseTableIndexUpdateDto dto) {
        UserJwt loginUser = UserRequest.getLoginUser();
        OperationService operationService = databaseStaticService.getConnectionById(loginUser.getUuid(), dto.getDataSourceId(), dto.getDatabaseName(), dto.getSchemaName());
        operationService.updateIndex(dto.getSchemaName(), dto.getTableName(), dto.getIndexName(), dto.getIndexDto());
        operationService.closeAll();
        return true;
    }

    @Override
    public Boolean deleteIndex(DatabaseTableIndexDelDto dto) {
        UserJwt loginUser = UserRequest.getLoginUser();
        OperationService operationService = databaseStaticService.getConnectionById(loginUser.getUuid(), dto.getDataSourceId(), dto.getDatabaseName(), dto.getSchemaName());
        operationService.deleteIndex(dto.getSchemaName(), dto.getTableName(), dto.getIndexName());
        operationService.closeAll();
        return true;
    }

    @Override
    public String[] getTableIndexTypeList(DatabaseTableIndexSelectDto dto) {
        AutoDataSource autoDataSource = autoDataSourceMapper.selectById(dto.getDataSourceId());
        if (autoDataSource == null) {
            throw new BusinessException("获取数据库异常，未找到数据");
        }
        OperationService operationService = backupServiceFactory.getBackupService(autoDataSource, autoExeSqlLogMapper);
        String[] typeList = operationService.getTableIndexTypeList();
        return typeList;
    }

    @Override
    public Boolean alterPk(DatabaseTableFiledPkDto dto) {
        UserJwt loginUser = UserRequest.getLoginUser();
        OperationService operationService = databaseStaticService.getConnectionById(loginUser.getUuid(), dto.getDataSourceId(), dto.getDatabaseName(), dto.getSchemaName());
        operationService.alterPk(dto.getSchemaName(), dto.getTableName(), dto.getFiledName(),dto.getPk());
        operationService.closeAll();
        return true;
    }
}
